import { Empty, Row, Col, Select, Tooltip } from 'antd';
import { Advice, Advisor } from '@antv/ava';
import { Chart } from '@berryv/g2-react';
import { DownOutlined } from '@ant-design/icons';
import i18n from '@/app/i18n';
import { customizeAdvisor, getVisAdvices } from './advisor/pipeline';
import { useEffect, useMemo, useState, useRef } from 'react';
import { defaultAdvicesFilter } from './advisor/utils';
import { AutoChartProps, ChartType, CustomAdvisorConfig, CustomChart, Specification } from './types';
import { customCharts } from './charts';
import { useTranslation } from 'react-i18next';
import { theme } from '../theme.js';
import { Line,Bar,Pie } from 'react-chartjs-2'
import DynamicChartComponent from '../DynamicChartComponent';
const { Option } = Select;


export const AutoChart = (props: AutoChartProps) => {
  const { data, chartType, scopeOfCharts, ruleConfig } = props;
  const { t } = useTranslation();
  const [advisor, setAdvisor] = useState<Advisor>();
  const [advices, setAdvices] = useState<Advice[]>([]);
  const [renderChartType, setRenderChartType] = useState<ChartType>();
  const [chartSize, setChartSize] = useState({ width: 0, height: 0 });
  useEffect(() => {
    const input_charts: CustomChart[] = customCharts;
    const advisorConfig: CustomAdvisorConfig = {
      charts: input_charts,
      scopeOfCharts: undefined,
      ruleConfig,
    };
    console.log(input_charts,advisorConfig,'advisorConfig')
    setAdvisor(customizeAdvisor(advisorConfig));
  }, [ruleConfig, scopeOfCharts]);
  useEffect(() => {
    if (data && advisor) {
      const avaAdvices = getVisAdvices({
        data,
        myChartAdvisor: advisor,
      });
      const filteredAdvices = defaultAdvicesFilter({
        advices: avaAdvices,
      });
      console.log(filteredAdvices,avaAdvices,data,advisor,'filteredAdvices')
      filteredAdvices.sort((a, b) => {
        return chartType.indexOf(b.type) - chartType?.indexOf(a.type);
      });

      setAdvices(filteredAdvices);

      setRenderChartType(filteredAdvices[0]?.type as ChartType);
    }
  }, [data, advisor, chartType]);
  useEffect(()=>{
    const width = window.innerWidth/100;
    const height = window.innerHeight/100;
    setChartSize({
      width:width*105000/1920,
      height:height*52000/1080
    })
    window.addEventListener('resize',()=>{
      const width = window.innerWidth/100;
      const height = window.innerHeight/100;
      setChartSize({
        width:width*105000/1920,
        height:height*52000/1080
      })
    })
  },[])
  const chartRef = useRef();
  function onInit() {
    const chart = chartRef.current;
    /* chart.tooltip({
      showTitle: true,
      itemTpl: `<li data-index={index} style="font-size: 40px;">
                  <span style="background-color:{color};width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px;"></span>
                  {name}: {value}
               </li>`,
    }) */
    chart.theme({ ...theme });
    chart.render();
  }
  const visComponent = useMemo(() => {
    console.log(renderChartType,advices,'11')
    const modelData =  {
      option:{
        backgroundColor: '#2c343c',
        title: {
            text: '珠海市主要指标的完成情况',
            left: 'center',
            textStyle: {
                color: '#ccc',
                fontFamily: 'Microsoft Yahei'
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['数值', '同比'],
            textStyle: {
                color: '#ccc',
                fontFamily: 'Microsoft Yahei'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: ['电信业务总量（亿元)', '电信业务收入（亿元)', '固定电话用户（万户）', '移动电话用户（万户）', '5G用户（万户）', '固定宽带用户（万户）', 'FTTH/O光纤接入用户（万户）'],
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    color: '#ccc',
                    fontFamily: 'Microsoft Yahei'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    color: '#ccc',
                    fontFamily: 'Microsoft Yahei'
                }
            }
        ],
        series: [
            {
                name: '数值',
                type: 'bar',
                barWidth: '30%',
                data: [25.0, 28.5, 52.2, 413.9, 231.7, 130.9, 125.1],
                itemStyle: {
                    color: '#3398DB'
                }
            },
            {
                name: '同比',
                type: 'bar',
                barWidth: '30%',
                data: [7.10, 3.60, null, null, null, null, null],
                itemStyle: {
                    color: '#7CFC00'
                }
            }
        ]
      }
        
    };
    return <DynamicChartComponent modelData={modelData} />
    /* Advices exist, render the chart. */
    if (advices?.length > 0) {
      const chartTypeInput = renderChartType ?? advices[0].type;
      const spec: Specification = advices?.find((item: Advice) => item.type === chartTypeInput)?.spec ?? undefined;
      
      console.log('spec',spec)
      // 添加翻译
      const tData:any[] = []
      if(spec.data&&Array.isArray(spec.data)){ 
        /* if(!spec.isTransform){
          spec.data.forEach((item:any)=>{
            if(spec.children&&Array.isArray(spec.children)){
              let numberKey = ''
              Object.values(spec.children[0].encode).map((key:any)=>{
                if(typeof item[key]==='number'){
                  numberKey = key
                }
              })
              if(numberKey){
                item[numberKey] = item[numberKey]/10000
              }
            }else if(spec.encode){
              let numberKey = ''
              Object.values(spec.encode).map((key:any)=>{
                if(typeof item[key]==='number'){

                  numberKey = key
                }
              })
              if(numberKey){
                item[numberKey] = item[numberKey]/10000
              }
            }
          })
        }
        spec.isTransform = true */
        if(spec.children&&Array.isArray(spec.children)){
        spec.children.map((item:any)=>{
          item.encode.x = t(item.encode.x)||item.encode.x;
          item.encode.y = t(item.encode.y)||item.encode.y
        })
        }else if(spec.encode){
          spec.encode.x = t(spec.encode.x)||spec.encode.x;
          spec.encode.y = t(spec.encode.y)||spec.encode.y;
          spec.encode.color = t(spec.encode.color)||spec.encode.color;
        }
        spec.data.map((item:any)=>{
          const itemObject = {}
          Object.keys(item).map((k:any)=>{
            itemObject[t(k)||k] = item[k] 
          })
          tData.push(itemObject)
        })
        
        spec.data = tData
      }
      if(spec.dataProps&&Array.isArray(spec.dataProps)){
        spec.dataProps.map((item:any)=>{
          item.name = t(item.name)||item.name
        })
      }
      
      
      /* if(chartTypeInput!="pie_chart"&&chartTypeInput!="donut_chart"){
        
      } */
      if (spec) {
        
        return <Chart key={chartTypeInput} options={{ ...spec, width: chartSize.width, height: chartSize.height}} ref={chartRef} onInit={onInit} />;
      }
    }
  }, [advices, renderChartType]);

  if (renderChartType) {
    return (
      <div>
        <Row justify="start" align="middle">
          <Col style={{fontSize:"calc(14vw * var(--w))"}}>{i18n.t('Advices')}</Col>
          <Col style={{ marginLeft: "calc(24vw * var(--w))",display:"flex" }}>
            <Select
              value={renderChartType}
              placeholder={'Chart Switcher'}
              style={{ width: "calc(180vw * var(--w))" ,fontSize:"calc(14vw * var(--w))"}}
              onChange={(value) => setRenderChartType(value)}
              size={'small'}
            >
              {advices?.map((item) => {
                const name = i18n.t(item.type);

                return (
                  <Option key={item.type} value={item.type}>
                    <Tooltip title={name} placement={'right'}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <DownOutlined />
                        <div style={{ marginLeft: '2px' }}>{name}</div>
                      </div>
                    </Tooltip>
                  </Option>
                );
              })}
            </Select>
          </Col>
        </Row>
        <div className="auto-chart-content" id="container">{visComponent}</div>
      </div>
    );
  }

  return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={'暂无合适的可视化视图'} />;
};

export * from './helpers';
